﻿using Dapper;
using MySql.Data.MySqlClient;
using SqlKata;
using SqlKata.Compilers;
using System;
using System.Data;

namespace Kele.Repository
{

    public class Database : IDisposable
    {
        public IDbConnection Connection { get; set; }
        public Compiler Compiler { get; set; }
        public Action<SqlResult> Logger = result => { };
        public int QueryTimeout { get; set; } = 30;

        public Database()
        {
            var connectionString = Config.DefaultConnectionString;
            //SqlMapper.AddTypeHandler(new JArrayTypeHandler());
            //SqlMapper.AddTypeHandler( new JObjectTypeHandler());
            Connection = new MySqlConnection(connectionString);
            Compiler = new MySqlCompiler();
            Logger = compiled =>
                {
                    Console.WriteLine(compiled.ToString());
                };
        }

        public SqlResult Compile(Query query)
        {
            var compiled = this.Compiler.Compile(query);

            this.Logger(compiled);

            return compiled;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    if (this.Connection != null)
                    {
                        this.Connection.Dispose();
                        this.Connection = null;
                    }
                }

                disposedValue = true;
            }
        }
    }
}
